import * as clouddb from '@agconnect/database-server';
import { t_born as Born } from './models/t_born';
import * as agconnect from '@agconnect/common-server';

const ZONE_NAME = "QuickStartDemo";
const TAG = 'cloudDB-->'

export class CloudDBZoneWrapper {
  logger;
  cloudDbZone;

  constructor(credential, logger) {
    this.logger = logger;
    try {
      // 初始化AGCClient
      logger.info(TAG + "begin to init agcClient");
      let agcClient;
      try {
        agcClient = agconnect.AGCClient.getInstance();
      } catch {
        agconnect.AGCClient.initialize(credential);
        agcClient = agconnect.AGCClient.getInstance();
      }
      // 初始化AGConnectCloudDB实例
      logger.info(TAG + "begin to init clouddb");
      let cloudDbInstance;
      try {
        cloudDbInstance = clouddb.AGConnectCloudDB.getInstance(agcClient);
      } catch {
        clouddb.AGConnectCloudDB.initialize(agcClient);
        cloudDbInstance = clouddb.AGConnectCloudDB.getInstance(agcClient);
      }
      // 创建CloudDBZoneConfig配置对象，并设置云侧CloudDBzone名称，打开CloudDBzone实例
      const cloudDBZoneConfig = new clouddb.CloudDBZoneConfig(ZONE_NAME);
      this.cloudDbZone = cloudDbInstance.openCloudDBZone(cloudDBZoneConfig);
    } catch (err) {
      logger.error(TAG + "init CloudDBZoneWrapper error: " + err);
    }
  }

  //更新信息
  async updateRecord(bornInfo, bornInfoData) {
    try {
      this.logger.info(TAG + "begin update");
      let operator = clouddb.CloudDBZoneObjectOperator.build(bornInfo)
        .update("bornYear", bornInfoData.bornYear)
        .update("bornName", bornInfoData.bornName)
      this.logger.info(TAG + "operator ", operator);
      let updateRes = await this.cloudDbZone.executeUpdate(operator);
      this.logger.info(TAG + "updateRes ", updateRes);
      return updateRes > 0;
    } catch (error) {
      this.logger.error(TAG + "executeupdate born failed.Err: " + error);
      return false;
    }
  }

  //新增记录
  async insertRecord(bornInfo) {
    if (!this.cloudDbZone) {
      this.logger.error(TAG + "CloudDBClient is null, try re-initialize it");
    }

    try {
      let res = await this.cloudDbZone.executeUpsert(bornInfo);
      this.logger.info(TAG + "Insert " + res + " records success");
      return res > 0;
    } catch (error) {
      this.logger.error(TAG + "executeInsert Records failed " + error);
      return false;
    }
  }

  // 删除,传入要删除的born的id数组，如：[1,2,3]
  async deleteRecord(bornList) {
    if (!this.cloudDbZone) {
      this.logger.error(TAG + "CloudDBClient is null, try re-initialize it");
    }

    try {
      let result = await this.cloudDbZone.executeDelete(bornList);
      this.logger.info(TAG + "Delete records,result:" + result);
      return result > 0;
    } catch (error) {
      this.logger.error(TAG + "executeDelete  failed " + error);
      return false;
    }
  }

  //in: [1,2]
  //out [{1,null,null},{2,null,null}]
  //根据born的id重新构建born对象列表
  getBornForDelete(bornList) {
    return bornList.map((id) => {
      let object = new Born();
      object.setId(id);
      return object
    });
  }

  // 查询所有信息
  // return: [{"id":1,"bornYear":2008,"bornName":"鼠"},{....},....]
  async queryAllDatas() {
    let dataList = [];
    if (!this.cloudDbZone) {
      this.logger.error(TAG + "CloudDBClient is null, try re-initialize it");
    }
    const query = clouddb.CloudDBZoneQuery.where(Born);
    try {
      const resp = await this.cloudDbZone.executeQuery(query);
      dataList = resp.getSnapshotObjects();
      this.logger.info(TAG + "query born success ");
    } catch (error) {
      this.logger.error(TAG + "query born failed ");
    }
    return dataList;
  }

  // 查询信息（根据主键ID查询）
  async queryDataById(id) {
    let dataList = [];
    if (!this.cloudDbZone) {
      this.logger.error(TAG + "CloudDBClient is null, try re-initialize it");
    }
    const query = clouddb.CloudDBZoneQuery.where(Born).equalTo(
      "id", id
    );
    try {
      const resp = await this.cloudDbZone.executeQuery(query);
      dataList = resp.getSnapshotObjects();
      this.logger.info(TAG + "query born success ");
    } catch (error) {
      this.logger.error(TAG + "query born failed ");
    }
    return dataList;
  }

  // 查询信息(根据year)
  async queryDataByYear(year) {
    let dataList = [];
    if (!this.cloudDbZone) {
      this.logger.error(TAG + "CloudDBClient is null, try re-initialize it");
    }
    const query = clouddb.CloudDBZoneQuery.where(Born)
      .equalTo("bornYear", year);
    try {
      const resp = await this.cloudDbZone.executeQuery(query);
      dataList = resp.getSnapshotObjects();
      this.logger.info(TAG + "query born success ");
    } catch (error) {
      this.logger.error(TAG + "query born failed. Err:" + JSON.stringify(error));
    }
    return dataList;
  }

  // 创建操作对象（同时主键赋值）
  getInfo(id) {
    let object = new Born();
    object.setId(id);
    return object;
  }

  //根据客户端传递过来的json对象构建服务端的Born对象
  getBorn(bornParamData) {
    let object = new Born();
    object.setId(bornParamData.id);
    object.setBornYear(bornParamData.bornYear);
    object.setBornName(bornParamData.bornName);

    return object;
  }
}
;
